// RedJey Graphics User Interface Library for J2ME Platform.
// Copyright (C) 2008 Yevgen Krapiva
//
// This library is free software; you can redistribute
// it and/or modify it under the terms of the
// GNU Lesser General Public License as published
// by the Free Software Foundation; either version 3.0
// of the License, or any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this library; if not, write to the Free Software Foundation, Inc.,
// 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//

package com.incrediblesoft.redjey;

/**
 * @author Yevgen Krapiva<br>
 *         Homepage: http://code.google.com/p/redjey/<br>
 *         Feedback: ykrapiva@gmail.com<br>
 *         Copyright (C) 2008 Yevgen Krapiva<br>
 */

import com.incrediblesoft.redjey.layouts.ColumnLayout;
import com.incrediblesoft.redjey.event.KeyEvent;

public class MenuBar extends Container
{
    protected Component prevFocusOwner;
    protected boolean focusCaptured;

    public MenuBar()
    {
        this(null);
    }

    public MenuBar(String styleClassName)
    {
        super(styleClassName);
        setLayout(new ColumnLayout());
        setFocusCycled(true);
    }

    public String getName()
    {
        return "MenuBar";
    }

    public void validateComponent()
    {                
        for (int i=0; i<components.size(); i++)
        {
            Component c = (Component) components.elementAt(i);
            if (c instanceof Menu) ((Menu) c).popupOrientation = Menu.ABOVE_PLACEMENT;
        }

        super.validateComponent();
    }

    /**
     * Prevents menu bar loosing a focus
     * @return
     */
    public boolean transferFocusDownCycle()
    {
        Component focusOwner = UIManager.getFocusOwner();
        if (focusOwner != null && focusOwner.parent == this)
            return focusOwner.transferFocus();
        return false;
    }

    protected void captureFocus()
    {
        prevFocusOwner = UIManager.getFocusOwner();
        Component newFocusOwner = getComponentAfter(null);
        if (newFocusOwner != null)
        {
            newFocusOwner.requestFocus();
            if (newFocusOwner instanceof Menu)
                ((Menu) newFocusOwner).open();
            focusCaptured = true;
        }
    }

    protected void looseFocus()
    {
        for (int i=0; i<components.size(); i++)
        {
            Component component = (Component) components.elementAt(i);
            if (component instanceof Menu)
                ((Menu) component).close();
        }

        if (prevFocusOwner != null)
            prevFocusOwner.requestFocus();
        prevFocusOwner = null;
        
        focusCaptured = false;
    }

}
